package com.hk.core.autoconfigure.exception.reactive;

import com.hk.commons.JsonResult;
import com.hk.commons.Status;
import com.hk.commons.util.SpringContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.MethodNotAllowedException;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.ServerWebInputException;
import reactor.core.publisher.Mono;


/**
 * 对于 webmvc异常的处理
 *
 * @author Kevin
 */
@RestControllerAdvice
public class WebfluxExceptionHandler extends AbstractExceptionHandler {

    /**
     * <p>
     * ServerWebInputException.<br/>
     * 响应状态码： 400
     * </p>
     *
     * @param e       e
     * @param exchange exchange
     * @return {@link JsonResult}
     */
    @ExceptionHandler(value = {ServerWebInputException.class})
    @ResponseStatus(HttpStatus.OK)
    public Mono<JsonResult<Void>> serverWebInputException(ServerWebInputException e, ServerWebExchange exchange) {
        error(e, e.getMessage(), exchange);
        return Mono.just(new JsonResult<>(Status.BAD_REQUEST, Status.BAD_REQUEST.getMessage()));
    }

    /**
     * <p>
     * 对于不是指定的方法请求时，将抛出 MethodNotAllowedException.<br/>
     * 响应状态码： 405
     * </p>
     *
     * @param e       e
     * @param exchange exchange
     * @return {@link JsonResult}
     */
    @ExceptionHandler(value = {ResponseStatusException.class})
    @ResponseStatus(HttpStatus.OK)
    public Mono<JsonResult<Void>> responseStatusException(MethodNotAllowedException e, ServerWebExchange exchange) {
        error(e, e.getMessage(), exchange);
        return Mono.just(new JsonResult<>(Status.METHOD_NOT_ALLOWED, SpringContextHolder.getMessage("access.resources.no.support.message", e.getHttpMethod())));
    }


}
